package com.rerun.common.config;

import cn.jiguang.common.ClientConfig;
import cn.jpush.api.JPushClient;
import com.rerun.common.jpush.JpushException;
import com.rerun.common.jpush.JpushOperations;
import com.rerun.common.jpush.Operations;
import com.rerun.common.util.Validator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ResourceBundle;

/**
 * The type J push config.
 *
 * @author dax.
 * @version v1.0
 * @since 2017 /11/6 17:09
 */
@Configuration
public class JPushConfig {
    private static final ResourceBundle JPUSH_CONFIG = ResourceBundle.getBundle("properties/jPush");
    private static final long DEFAULT_TIME_TO_LIVE = 86400;
    private static final JPushClient JPUSH_CLIENT;

    static {
        String secretKey = JPUSH_CONFIG.getString("jPush.secretKey");
        String appKey = JPUSH_CONFIG.getString("jPush.appKey");
        int maxRetryTimes = Integer.parseInt(JPUSH_CONFIG.getString("jPush.maxRetryTimes")) ;
        int timeout = Integer.parseInt(JPUSH_CONFIG.getString("jPush.connectionTimeout"));
        long timeToLive =Long.parseLong(JPUSH_CONFIG.getString("jPush.timeToLive")) ;
//        boolean apnsProduction = (boolean) JPUSH_CONFIG.getObject("jPush.apnsProduction");
        ClientConfig config = ClientConfig.getInstance();
        config.setMaxRetryTimes(maxRetryTimes);
        config.setConnectionTimeout(timeout);
        config.setTimeToLive(Validator.defaultIfNull(timeToLive, DEFAULT_TIME_TO_LIVE));
        config.setApnsProduction(true);
        JPUSH_CLIENT = new JPushClient(secretKey, appKey, null, config);
    }

    /**
     * Operations operations.
     *
     * @return the operations
     */
    @Bean
    public Operations operations() {
        JpushOperations jpushOperations = new JpushOperations();
        try {
            jpushOperations.setjPushClient(builder());
        } catch (JpushException e) {
            e.printStackTrace();
        }
        return jpushOperations;
    }

    private static JPushClient builder() throws JpushException {
        if (JPUSH_CLIENT != null) {
            return JPUSH_CLIENT;
        }
        throw new JpushException("JpushClient failed to initialize");
    }
}
